package com.jsaas.sys.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;

import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jsaas.common.Constant;
import com.jsaas.model.User;

/**   
 * @Title: UserService.java 
 * @Package com.jsaas.sys.service 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @author tuozq 
 * @date 2017年11月6日 上午9:37:22 
 * @version V1.0   
 */
public class UserService {
	
	public static final String DEFAULT_PASSWORD = "123456";//用户默认密码
	public static final String USER_PERMISSION_CACHE = "user_permission:";//用户权限缓存名称前缀
	public static final String USER_MENU_CACHE = "user_menu:";//用户菜单缓存名称前缀
	
	
	public User sha1Password(User user){
		//随机数 + 用户账号作为salt值
		String salt = new SecureRandomNumberGenerator().nextBytes().toHex() + user.getAccount();
		// 对密码加盐进行1024次SHA1加密 (必须与shiro文件中credentialsMatcher.hashAlgorithmName  credentialsMatcher.hashIterations 保持一致，否则登录时密码验证会失败)
		String _password = new SimpleHash(Constant.HASHALGORITHMNAME, user.getPassword(), salt, Constant.HASH_ITERATIONS).toHex();
		user.setSalt(salt);
		//通过盐值加密密码
		user.setPassword(_password);
		return user;
	}

	public Ret save(User user){
		if(user.isExist("account", user.getAccount())){
			return Ret.fail("msg", "用户账号 " + user.getAccount() + " 已经存在，不能重复。");
		}
		if(StrKit.isBlank(user.getId())){
			//加密密码
			user.setPassword(DEFAULT_PASSWORD);
			sha1Password(user);
		}
		user.save();
		return Ret.ok().set("user", user);
	}
	
	/**
	 * 获取用户所拥有的所有权限
	 * @param userId
	 * @return
	 */
	public List<String> findPermissionByUserId(String userId){
		List<String> results = new ArrayList<String>();
		String sql = Db.getSql("user.findPermissionByUserId");
		List<Record> list = Db.findByCache(Constant.COMMON_CACHE, USER_PERMISSION_CACHE + userId, sql, userId);
		for (Record record : list) {
			results.add(record.getStr("permission"));
		}
		return results;
	}
	
	/**
	 * 获取首页菜单数据
	 * @return
	 */
	public Ret findMenuByUserId(String userId){
		Map<Object, List<Kv>> results = new HashMap<Object, List<Kv>>();
		String sql = Db.getSql("menu.findMenuByUserId");
		List<Record> menus = Db.findByCache(Constant.COMMON_CACHE, USER_MENU_CACHE + userId, sql, userId);
		
		for (Record record : menus) {
			if(!results.containsKey(record.getStr("menu_name"))){
				List<Kv> list = new ArrayList<Kv>();
				results.put(record.getStr("menu_name"), list);
				list.add(Kv.by("submenu_name", record.get("submenu_name")).set("submenu_no", record.getStr("submenu_no")).set("submenu_url", record.getStr("submenu_url")).set("submenu_icon", record.getStr("submenu_icon")).set("menu_icon", record.getStr("menu_icon")));
			}else{
				List<Kv> list = results.get(record.getStr("menu_name"));
				list.add(Kv.by("submenu_name", record.get("submenu_name")).set("submenu_no", record.getStr("submenu_no")).set("submenu_url", record.getStr("submenu_url")).set("submenu_icon", record.getStr("submenu_icon")).set("menu_icon", record.getStr("menu_icon")));
			}
		}
		
		return Ret.ok().set("data", results);
	}


}
